import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi, register as registerApi, getUserInfo, logout as logoutApi } from '../api/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string | null>(localStorage.getItem('token'))
  const userInfo = ref<any>(null)
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)

  // 方法
  // 登录
  const login = async (credentials: { username: string; password: string }) => {
    try {
      loading.value = true
      const response = await loginApi(credentials)
      
      if (response.success && response.data.token) {
        token.value = response.data.token
        localStorage.setItem('token', response.data.token)
        
        // 设置用户信息
        userInfo.value = response.data.user
        
        return { success: true }
      }
      
      return { success: false, message: response.message || '登录失败' }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.message || '登录失败，请检查用户名和密码' 
      }
    } finally {
      loading.value = false
    }
  }

  // 注册
  const register = async (userData: { username: string; email: string; password: string }) => {
    try {
      loading.value = true
      const response = await registerApi(userData)
      
      return { success: response.success, data: response.data, message: response.message }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.message || '注册失败，请稍后再试' 
      }
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      if (!token.value) return null
      
      const response = await getUserInfo()
      
      if (response.success) {
        userInfo.value = response.data
        return response.data
      } else {
        // 如果获取用户信息失败，可能是token过期，清除登录状态
        logout()
        return null
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，可能是token过期，清除登录状态
      logout()
      return null
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      if (token.value) {
        await logoutApi()
      }
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      // 无论API调用是否成功，都清除本地状态
      token.value = null
      userInfo.value = null
      localStorage.removeItem('token')
    }
  }

  // 初始化用户信息
  const initUserInfo = async () => {
    if (token.value && !userInfo.value) {
      await fetchUserInfo()
    }
  }

  return {
    // 状态
    token,
    userInfo,
    loading,
    
    // 计算属性
    isLoggedIn,
    
    // 方法
    login,
    register,
    fetchUserInfo,
    logout,
    initUserInfo
  }
})